package com.jpress.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jpress.dao.DAOBlog;
import com.jpress.facade.Facade;
import com.jpress.model.Admin;
import com.jpress.model.Blog;
import com.jpress.model.CustomPage;

/**
 * Servlet implementation class CadastroCustomPageServlet
 * Cadastro de custom Page
 */
@WebServlet("/novacustompage.do")
public class CadastroCustomPageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public CadastroCustomPageServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Facade facade = new Facade();
		CustomPage novaCustomPage = new CustomPage();
		String titulo = request.getParameter("titulo");
		String conteudo = request.getParameter("conteudo");
		String mensagemValidacao = "";
		if(titulo == "" || conteudo == ""){
			if(titulo == ""){
				mensagemValidacao += "O campo [TITULO] deve ser preenchido.<br />";
			}

			if(conteudo == ""){
				mensagemValidacao += "O campo [CONTEUDO] deve ser preenchido.<br />";
			}
			request.setAttribute("mensagemValidacao", mensagemValidacao);
			request.setAttribute("corErro", "#FFECEC");
			RequestDispatcher view1 = request.getRequestDispatcher("novacustompage.jsp");
			view1.forward(request, response);
		}else{
			try {
				//HttpSession session = request.getSession();
				//Admin logado = (Admin) session.getAttribute("logado");
				int idblog =  Integer.parseInt((String)request.getParameter("blog"));
				DAOBlog daoBlog = new DAOBlog();
				Blog blogAtual = daoBlog.findById(idblog);
				novaCustomPage.setBlog(blogAtual);
				//blogAtual.adicionarCustomPage(novaCustomPage);
				novaCustomPage.setTitulo(titulo);
				novaCustomPage.setConteudo(conteudo);
				System.out.println(novaCustomPage);
				RequestDispatcher view2 = request.getRequestDispatcher("novacustompage.jsp");
				if(facade.cadastrarCustomPage(novaCustomPage)){
					request.setAttribute("mensagemLog", "CustomPage cadastrada com sucesso!");
					request.setAttribute("corErro", "#E2FFBB");
				}else{
					request.setAttribute("mensagemLog", "Erro ao cadastrar customPage.");
				}
				view2.forward(request, response);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
